package com.chen.jwt.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.jwt.entity.User;
import com.chen.jwt.service.UserService;
import com.chen.jwt.utils.JWTUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.chen.jwt.utils.JWTUtils.getTokenInfo;


/**
 * @author 若晨
 * @version 1.0.0
 * @ClassName UserContolloer.java
 * @Description TODO
 * @createTime 2022年08月02日 19:45:00
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(User user){
        log.info("用户名：[{}]",user.getName());
        log.info("密码：[{}]",user.getPassword());
        Map<String,Object> map =  new HashMap<>();
        try {
            User result = userService.login(user);

            Map<String,Object> payload = new HashMap<>();
            payload.put("id",result.getId());
//            payload.put("name",result.getName());
            //生成JWT的令牌
            String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        } catch (Exception e) {
           map.put("state",false);
           map.put("msg",e.getMessage());
        }
        return map;
    }
    @PostMapping("/user/test")
    public Map<String,Object> test(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
            //处理自己的业务逻辑
        String token = request.getHeader("token");

        User user = getTokenInfo(token);
        log.info("用户id：[{}]",user.getId());
        log.info("用户名：[{}]",user.getName());
        log.info("用户密码：[{}]",user.getPassword());
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }

}
